import React from 'react';
import ReactDOM from 'react-dom';
import Router from 'next/router';
import { ListView, Icon } from 'antd-mobile';

import HeadC from '../../src/components/layout/head';
import FooterC from '../../src/components/layout/footer';
import CustomSearchBar from '../../src/containers/customSearchBar';
import SingleItem from '../../src/components/singleItem';

import { postRequest, getRequest } from '../../tools/requests';

import './index.css';

const NUM_ROWS = 20;
let pageIndex = 1;
let GoodsListsCache = [], HistoryKeyWord, GlobalrData;

function genData(pIndex = 1) {
  const dataBlob = {};
  for (let i = 0; i < NUM_ROWS; i++) {
    const ii = (pIndex * NUM_ROWS) + i;
    dataBlob[`${ii}`] = `row - ${ii}`;
  }
  return dataBlob;
}

export default class SearchPage extends React.Component {
	static async getInitialProps() {
		let hotSearchList;
		const result = await postRequest('hot_search_keyword/')
		if (result.success) {
			hotSearchList = result.data;
		}
		return {
			title: 'coupon',
			description: '',
			links: '',
			ogImage: '',
			hotSearchList,
		}
	}
	constructor(props) {
		super(props);
    const dataSource = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row1 !== row2,
    });

    this.state = {
    	goodsLists: [],
      dataSource,
			isLoading: false,
			searchKeyword: '',
			currentHotBtnIndex: undefined
    };
	}
	componentDidMount() {
		if (window.goodsListsCache && window.goodsListsCache.length > 0 && window.globalrData) {
			this.rData = window.globalrData;
			this.setState({
				dataSource: this.state.dataSource.cloneWithRows(this.rData),
				isLoading: false,
				goodsLists: window.goodsListsCache,
				searchKeyword: window.historyKeyWord,
			})
		}
	}
	async onEndReached(event) {
		event.preventDefault();
		if (this.state.goodsLists.length > 0) {
			if (this.state.isLoading && !this.state.hasMore) {
				return;
			}
			this.setState({ isLoading: true });
			let pageAdd = ++pageIndex;
			const result = await 
			await getRequest('search_goods/', {page: pageIndex, page_size: NUM_ROWS, searchName: this.state.searchKeyword});
			if (result.result_list && result.result_list.length > 0) {
				this.rData = { ...this.rData, ...genData(pageAdd) };

				await this.setState({
					goodsLists: result.result_list,
					dataSource: this.state.dataSource.cloneWithRows(this.rData),
					isLoading: false,
				});
				GoodsListsCache.push(...this.state.goodsLists);
				GlobalrData = this.rData;
			}
		}
	}
	async searchSingleResult(searchKeyword, curId) {
		let goodsLists = [];
		pageIndex = 1; //重新获取一个类目的数据时，对pageIndex进行初始化；
		await this.setState({
			dataSource: this.state.dataSource.cloneWithRows({}),
			isLoading: true,
			goodsLists: [],
		})
		await this.setState({ searchKeyword })
		const fetchGoodsLists = await getRequest('search_goods/', {page: pageIndex, page_size: NUM_ROWS, searchName: this.state.searchKeyword});
		if (fetchGoodsLists.result_list && fetchGoodsLists.result_list.length > 0) {
			goodsLists = fetchGoodsLists.result_list
		}
		this.rData = genData();
		this.setState({
			dataSource: this.state.dataSource.cloneWithRows(this.rData),
			isLoading: false,
			goodsLists,
			currentHotBtnIndex: curId
		}, () => {
			GoodsListsCache = this.state.goodsLists;
			HistoryKeyWord = this.state.searchKeyword;
			GlobalrData = this.rData;
		});
	}
	render() {
		const { title, description, links, ogImage, hotSearchList } = this.props;
		const row = (rowData, sectionID, rowID) => {
      let indexID = rowID > 20 ? rowID % 20 === 0 ? 19 : (rowID % 20) - 1 : rowID;
      let objItem = this.state.goodsLists[indexID] ? (
        <SingleItem key={rowID} item={this.state.goodsLists[indexID]}></SingleItem>
      ) : null;
      return objItem
    };
		return (
			<div className="app-block" style={{height: this.state.appHeight}}>
				<HeadC 
					title={title} 
					description={description}
					links={links}
					ogImage={ogImage}
				></HeadC>
				<CustomSearchBar 
					isHomepage={true} 
					searchSingleResult={this.searchSingleResult.bind(this)}
					placeholderVal={this.state.searchKeyword}
				/>
				<div className="hot-search-block" style={{margin: '76px 0 20px', padding: '0 10px'}}>
					<h4> 热门搜索： </h4>
					<div className="hot-list-search-block">
						{
							hotSearchList.length > 0 ? hotSearchList.map(item => (
								<span
									className={this.state.currentHotBtnIndex == item.id ? 'activeIndex': null}
									key={item.id} 
									onClick={() => this.searchSingleResult(item.name, item.id)}
								>
									{item.name}
								</span>
							)) : ''
						}
					</div>
				</div>
				<ListView
          ref={el => this.lv = el}
          dataSource={this.state.dataSource}
          renderFooter={() => (<div style={{ padding: '15px', textAlign: 'center' }}>
            {this.state.isLoading ? <Icon type="loading" /> : ''}
          </div>)}
					renderRow={row}
					className="am-list"
          pageSize={4}
          useBodyScroll
          onScroll={() => { console.log('scroll'); }}
          scrollRenderAheadDistance={500}
          onEndReached={this.onEndReached.bind(this)}
          onEndReachedThreshold={10}
          // style={{marginTop: '121px'}}
        />
				<FooterC src="../../static/images/police.png" />
			</div>
		)
	}
}

const handleChangeUrl = (url) => {
	const reg = /^\/details/;
	if (reg.test(url)) {
		window.goodsListsCache = GoodsListsCache;
		window.historyKeyWord = HistoryKeyWord;
		window.globalrData = GlobalrData;
	} else if(url === '/search') {
		return
	} else {
		window.goodsListsCache = [];
		window.historyKeyWord = '';
		window.globalrData = null;
	}
}

Router.events.on('routeChangeStart', handleChangeUrl)